import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Logininfor } from "./entities/logininfor.entity";
import { Repository } from "typeorm";
import { InjectRedis, Redis } from "@nestjs-modules/ioredis";
import { SharedService } from "src/shared/shared.service";
import { Request } from "express";
import * as moment from "moment";
import { User } from "../../system/user/entities/user.entity";
import { USER_ONLINE_KEY } from "src/common/constants/redis.constant";

@Injectable()
export class LogService {
  constructor(
    @InjectRepository(Logininfor) private readonly logininforRepository: Repository<Logininfor>,
    @InjectRedis() private readonly redis: Redis,
    private readonly sharedService: SharedService,
  ) {}

  // 新增登录日志
  async addLogininfor(request: Request, msg: string, token?: string) {
    const logininfor = new Logininfor();
    const { username } = request.body;
    logininfor.userName = username;
    logininfor.ipaddr = this.sharedService.getReqIP(request);
    logininfor.loginLocation = await this.sharedService.getLocation(logininfor.ipaddr);
    logininfor.loginTime = moment().format("YYYY-MM-DDTHH:mm:ss");

    if (token) {
      // 如果登录成功，就记录这个登录信息，方便在线用户查询
      const user: User = (request as any).user;
      const data = { dept_name: "", tokenId: token };
      if (user.dept) {
        data.dept_name = user.dept.dept_name;
      }
      const loginUser = Object.assign(logininfor, data);
      await this.redis.set(
        `${USER_ONLINE_KEY}:${user.userId}`,
        JSON.stringify(loginUser),
        "EX",
        60 * 60 * 24,
      );
    }
    return await this.logininforRepository.save(logininfor);
  }
}
